package org.example.controller;

import org.example.annotation.LoginCheck;
import org.example.domain.Message;
import org.example.domain.User;
import org.example.service.imp.MessageServiceImp;
import org.example.service.imp.UserServiceImp;
import org.example.util.CommonParam;
import org.example.util.HutoolUtil;
import org.example.util.UserThreadLocalUtil;
import org.example.vo.CommentVO;
import org.example.vo.LimitPageVO;
import org.example.vo.MessageVO;
import org.example.vo.SystemMessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/message/")
public class MessageController {
    @Autowired
    private HutoolUtil hutoolUtil;
    @Autowired
    private MessageServiceImp messageServiceImp;
    @Autowired
    private UserThreadLocalUtil userThreadLocalUtil;
    @Autowired
    private UserServiceImp userServiceImp;
    @LoginCheck
    @GetMapping("myMessage")
    public String messagePage(@RequestParam(value = "curr",required = false) Integer curr,Model model){
        User user = userThreadLocalUtil.get();
        int start =  curr == null || curr<=0? 0 : (curr-1)*CommonParam.DEFAULT_LIMIT;
        List<Message> messages = messageServiceImp.searchTo(user.getId(),start,CommonParam.DEFAULT_LIMIT);
        Map<String, MessageVO> messageGroup = new HashMap<>();
        int totalNoReadCount = 0;
        for (Message temp : messages){
           if (!messageGroup.containsKey(temp.getConversationId())){
               MessageVO messageVO = new MessageVO();
               User user1 = userServiceImp.searchById(temp.getFromId());
               messageVO.setMessageFromUser(user1);
               ArrayList<Message> messageArrayList = new ArrayList<>();
               if (temp.getStatus() == 1){
                   //未读
                   totalNoReadCount++;
                   messageVO.setNoReadCount(messageVO.getNoReadCount()+1);
               }
               messageArrayList.add(temp);
               messageVO.setMessageList(messageArrayList);
               messageGroup.put(temp.getConversationId(),messageVO);

               continue;
           }
            MessageVO messageVO = messageGroup.get(temp.getConversationId());
            if (temp.getStatus() == 1){
                //未读
                totalNoReadCount++;
                messageVO.setNoReadCount(messageVO.getNoReadCount()+1);
            }
            messageVO.getMessageList().add(temp);
        }
        model.addAttribute("totalNoReadCount",totalNoReadCount);
        model.addAttribute("messages",messageGroup);
        // 分页参数
        LimitPageVO limitPageVO = hutoolUtil.limitPage(curr == null ? 1 : curr, CommonParam.DEFAULT_LIMIT, messageServiceImp.searchCount(user.getId()));
        limitPageVO.setPath("/message/myMessage");
        model.addAttribute("limitParam",limitPageVO);
        return "site/letter";
    }
    @LoginCheck
    @GetMapping("detailPage/{fromId}")
    public String detailPage(@PathVariable(value = "fromId") Integer fromId,Model model){
        User user = userThreadLocalUtil.get();
        int id = user.getId();
        String conversation_id = fromId>=id?id+"_"+fromId:fromId+"_"+id;
        List<Message> messageList = messageServiceImp.searchMessageByConversationId(conversation_id);
        if (messageList == null || messageList.size() == 0){
            User user1 = userServiceImp.searchById(fromId);
            model.addAttribute("fromUserName",user1.getUsername());
            return "site/letter-detail";
        }

        //当前我们点击消息列表时 这些消息的status 需要改变 额 感觉有点麻烦 (查出来 然后就马上修改  两次数据库的读写)  记录一个需要修改的ids
        ArrayList<Integer> ids = new ArrayList<>();
        //将from 和 to 两个人的信息拆分
        Map<Integer,MessageVO> result = new HashMap<>();
        for (Message temp : messageList){
            if (temp.getStatus() == 1){
                ids.add(temp.getId());
            }
            int tempFromId = temp.getFromId();
            if (!result.containsKey(tempFromId)){
                MessageVO messageVO = new MessageVO();
                User fromUser = userServiceImp.searchById(tempFromId);
                messageVO.setMessageFromUser(fromUser);
                List<Message> innerLit = new ArrayList<>();
                innerLit.add(temp);
                messageVO.setMessageList(innerLit);
                result.put(tempFromId,messageVO);
                continue;
            }
            MessageVO tempVO = result.get(tempFromId);
            tempVO.getMessageList().add(temp);
        }
        //批量修改
        if (ids.size()>=1){
            messageServiceImp.changeNoRead(ids);
        }
        model.addAttribute("messages",result);
        if (result.containsKey(id)){
            model.addAttribute("self",id);
        }
        if (result.containsKey(fromId)){
            model.addAttribute("other",fromId);
        }


        return "site/letter-detail";
    }
    @LoginCheck
    @GetMapping("remove/{messageId}")
    public String remove(@RequestParam("messageId") Integer messageId){
        if (messageId == null || messageId<=0){
            return "失败";
        }
        messageServiceImp.remove(messageId);
        return "成功";
    }
    //这个方法发现一个问题 我发私信给别人   这个会话是我们两个人的  我打开了这个私信 这个私信状态会被改变成已读  但是接受私信的那个人 并没有读  数据库应该在设计两个字段 我读还是他读  算啦 不写了
    @LoginCheck
    @ResponseBody
    @GetMapping("sendSecretMessage")
    public String sendSecretMessage(String toUserName,String content){
        if (hutoolUtil.stringIsEmpty(toUserName)) return "用户不存在";
        if (hutoolUtil.stringIsEmpty(content)) return "内容不能为空";
        User user = userServiceImp.searchByUsername(toUserName);
        if (user==null) return "用户不存在";
        User self = userThreadLocalUtil.get();
        String conversation_id = self.getId()>=user.getId()?user.getId() +"_"+self.getId():self.getId()+"_"+user.getId();
        Message message = new Message();
        message.setFromId(self.getId());
        message.setToId(user.getId());
        message.setContent(content);
        message.setStatus((byte)1);
        message.setConversationId(conversation_id);
        messageServiceImp.saveOne(message);
        return "发送成功";
    }
    @LoginCheck
    @GetMapping("systemPage.html")
    public String systemPage(Model model){
        User user = userThreadLocalUtil.get();
        int userId = user.getId();
        //页面需要
        // 总共的未读消息  评论，点赞，关注的未读数量  分别获取排序后的第一个数据
        int totalSystemNoReadCount = messageServiceImp.getSystemNoReadCount(userId,"system");
        int commentSystemNoReadCount = messageServiceImp.getSystemNoReadCount(userId,CommonParam.KAFKA_TOPIC_COMMENT);
        int likeSystemNoReadCount = messageServiceImp.getSystemNoReadCount(userId,CommonParam.KAFKA_TOPIC_LIKE);
        int followSystemNoReadCount = messageServiceImp.getSystemNoReadCount(userId,CommonParam.KAFKA_TOPIC_FOLLOW);
        model.addAttribute("totalSystemNoReadCount",totalSystemNoReadCount);
        model.addAttribute("commentSystemNoReadCount",commentSystemNoReadCount);
        model.addAttribute("likeSystemNoReadCount",likeSystemNoReadCount);
        model.addAttribute("followSystemNoReadCount",followSystemNoReadCount);
        if (commentSystemNoReadCount>0){
            Message firstNoReadCommentMessage = messageServiceImp.searchSystemMessage(userId,CommonParam.KAFKA_TOPIC_COMMENT,0,1).get(0);
            String content = firstNoReadCommentMessage.getContent();
            if (!hutoolUtil.stringIsEmpty(content)){
                messageServiceImp.changeSystemMessage(firstNoReadCommentMessage);
                model.addAttribute("firstNoReadCommentMessage",firstNoReadCommentMessage);
            }
        }
        if (likeSystemNoReadCount>0){
            Message firstNoReadLikeMessage = messageServiceImp.searchSystemMessage(userId,CommonParam.KAFKA_TOPIC_LIKE,0,1).get(0);
            String content = firstNoReadLikeMessage.getContent();
            if (!hutoolUtil.stringIsEmpty(content)){
                messageServiceImp.changeSystemMessage(firstNoReadLikeMessage);
                model.addAttribute("firstNoReadLikeMessage",firstNoReadLikeMessage);
            }
        }
        if (followSystemNoReadCount>0){
            Message firstNoReadFollowMessage = messageServiceImp.searchSystemMessage(userId,CommonParam.KAFKA_TOPIC_FOLLOW,0,1).get(0);
            String content = firstNoReadFollowMessage.getContent();
            if (!hutoolUtil.stringIsEmpty(content)){
                messageServiceImp.changeSystemMessage(firstNoReadFollowMessage);
                model.addAttribute("firstNoReadFollowMessage",firstNoReadFollowMessage);
            }
        }

        return "site/notice";
    }
    @LoginCheck
    @GetMapping("systemMessageDetail")
    public String systemMessageDetail(String type,@RequestParam(value = "currPage",required = false) Integer currPage,Model model){
        if (hutoolUtil.stringIsEmpty(type)){
            throw new RuntimeException("消息类型不确认");
        }
        User user = userThreadLocalUtil.get();
        if (currPage == null || currPage<=0) currPage = 1;
        int systemMessageCount = messageServiceImp.getSystemMessageCountByType(user.getId(), type);
        LimitPageVO limitPageVO = hutoolUtil.limitPage(currPage, CommonParam.DEFAULT_LIMIT, systemMessageCount);
        limitPageVO.setPath("/message/systemMessageDetail?type="+type);
        //获取对应类型的系统消息  页面展示需要分页  展示后全部设置为已读
        int start = (limitPageVO.getCurrent()-1)*CommonParam.DEFAULT_LIMIT;
        List<Message> messageList = messageServiceImp.searchSystemMessage(user.getId(), type, start, CommonParam.DEFAULT_LIMIT);
        //需要体现 谁 做了什么(点赞 关注 评论) 你的 什么(帖子 评论 用户)  需要指定跳转
        List<SystemMessageVO> systemMessageVOS = messageServiceImp.systemMessagesToVOs(messageList);
        model.addAttribute("limitParam",limitPageVO);
        model.addAttribute("systemMessages",systemMessageVOS);
        //更改这些消息的状态
        List<Integer> ids = new ArrayList<>();
        for (int i = 0;i<messageList.size();i++){
            Message message = messageList.get(i);
            ids.add(message.getId());
        }
        messageServiceImp.changeNoRead(ids);
        return "site/notice-detail";
    }
}
